import React, { useState, useMemo, useCallback } from 'react';
import { Table } from 'antd';
import Sorter from './sorter'

export default ({
    columns,
    sortClear,
    onSortChange=()=>{},
    ...tableProps
})=>{
    const [sortField,setSortField]=useState()
    
    const handleSortChange=useCallback((sortData={})=>{
        setSortField(sortData.field)
        onSortChange(sortData)
    },[onSortChange])
    
    const cols=useMemo(()=>{
        return columns.map(col=>{
            if(col.sort){
                const {
                    title,
                    sort,
                    ...colProps
                }=col

                col={
                    ...colProps,
                    title:()=>(
                        <Sorter
                            title={title}
                            field={colProps.dataIndex}
                            onChange={handleSortChange}
                            clear={sortClear || sortField!==colProps.dataIndex} 
                        />
                    )
                }
            }
            return col
        })
    },[columns, handleSortChange, sortClear, sortField])


    
    return (
        <Table 
            columns={cols}
            {...tableProps}
            pagination={false}
        />
    )
}
